<template>
  <div class="randomAccess">
    <!-- 筛选条件 -->
    <ContentWrap>
      <el-form
        ref="queryFormRef"
        class="-mb-15px"
        :model="queryParams"
        :inline="false"
        label-width="130px"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="姓名" prop="patientName">
              <el-input v-model="queryParams.patientName" placeholder="请输入姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="身份证号码" prop="idNumber">
              <el-input v-model="queryParams.idNumber" placeholder="请输入身份证号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="随访日期" prop="followUpDate">
              <!-- <el-date-picker
                v-model="queryParams.followUpDate"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="!w-240px"
              /> -->
              <div class="time-box">
                <el-date-picker
                  style="width: 125px"
                  v-model="queryParams.lastFollowupStime"
                  size="mini"
                  type="date"
                  :editable="false"
                  :clearable="true"
                  placeholder="开始日期"
                  :disabled-date="lastFollowupDisableStartDate"
                />
                <span class="time-line">-</span>
                <el-date-picker
                  style="width: 125px"
                  v-model="queryParams.lastFollowupEtime"
                  size="mini"
                  :editable="false"
                  :clearable="true"
                  type="date"
                  placeholder="结束日期"
                  :disabled-date="lastFollowupDisableEndDate"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="下次随访日期" prop="nextFollowUpDate">
              <!-- <el-date-picker
                v-model="queryParams.nextFollowUpDate"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="!w-240px"
              /> -->
              <div class="time-box">
                <el-date-picker
                  style="width: 125px"
                  v-model="queryParams.nextFollowupStime"
                  size="mini"
                  type="date"
                  :editable="false"
                  :clearable="true"
                  placeholder="开始日期"
                  :disabled-date="nextFollowupDisableStartDate"
                />
                <span class="time-line">-</span>
                <el-date-picker
                  style="width: 125px"
                  v-model="queryParams.nextFollowupEtime"
                  size="mini"
                  :editable="false"
                  :clearable="true"
                  type="date"
                  placeholder="结束日期"
                  :disabled-date="nextFollowupDisableEndDate"
                />
              </div>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="危险性评估" prop="riskAssessment">
              <el-select
                v-model="queryParams.riskAssessment"
                placeholder="请选择危险性评估"
                clearable
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.RISK_ASSESSMENT)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item label="目前症状" prop="currentSymptomsDetail">
              <el-select
                v-model="queryParams.currentSymptomsDetail"
                placeholder="请选择目前症状"
                clearable
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.SYMPTOMS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="服药依从性" prop="medicationAdherence">
              <el-select
                v-model="queryParams.medicationAdherence"
                placeholder="请选择服药依从性"
                clearable
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.MEDICATION_ADHERENCE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="随访形式" prop="followUpMode">
              <el-select v-model="queryParams.followUpMode" placeholder="请选择随访形式" clearable>
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.RANDOM_ACCESS_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="失访原因" prop="lostContactReason">
              <el-select
                v-model="queryParams.lostContactReason"
                placeholder="请选择失访原因"
                clearable
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.LOST_REASON)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="危险行为" prop="dangerousBehaviorsFlag">
              <el-select
                v-model="queryParams.dangerousBehaviorsFlag"
                placeholder="请选择危险行为"
                clearable
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.HAS_DANGER_BEHAVIOR)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关锁情况" prop="seclusionStatus">
              <el-select
                v-model="queryParams.seclusionStatus"
                placeholder="请选择关锁情况"
                clearable
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.LOCK_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="治疗效果" prop="treatmentEffect">
              <el-select
                v-model="queryParams.treatmentEffect"
                placeholder="请选择治疗效果"
                clearable
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.TREATMENT_EFFECT)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="随访病情分类" prop="currentFollowupType">
              <el-select
                v-model="queryParams.currentFollowupType"
                placeholder="请选择随访病情分类"
                clearable
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.FOLLOWUP_DISEASE_CLASSIFICATION)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="当前分库状态" prop="currentOrgSubDbStatus">
              <el-select
                v-model="queryParams.currentOrgSubDbStatus"
                placeholder="请选择当前管理单位分库状态"
                clearable
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.SUB_LIBRARY_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="text-right">
            <el-form-item>
              <el-button type="primary" @click="handleQuery" v-hasPermi="['follow:up:query']"
                >查询</el-button
              >
              <el-button @click="resetQuery">重置</el-button>
              <el-button type="primary" @click="handleImport" v-hasPermi="['follow:up:import']">
                导入
              </el-button>
              <el-button
                type="success"
                @click="handleExport"
                :loading="exportLoading"
                v-hasPermi="['follow:up:export']"
              >
                模板下载
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <div class="content">
        <!-- 区域树 -->
        <div class="tree-box">
          <RegionTree v-model:checkedKeys="selectedKeys" :isExpand="true" :checkStrictly="false" />
        </div>
        <div style="width: 80%; height: calc(100vh - 450px)">
          <el-table
            size="large"
            v-loading="loading"
            :data="lists"
            border
            style="width: 100%"
            height="90%"
          >
            <!-- 序号 -->
            <el-table-column type="index" label="序号" width="80" align="center" fixed />
            <el-table-column
              label="患者编号"
              prop="patientCode"
              width="180"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="姓名"
              prop="patientName"
              width="80"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column label="性别" prop="gender" width="80" align="center">
              <template #default="scope">
                {{ getDictLabel(DICT_TYPE.GENDER, scope.row.gender) }}
              </template>
            </el-table-column>
            <el-table-column
              label="证件号"
              prop="idNumber"
              width="180"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column label="随访日期" prop="followUpDate" width="150" align="center">
              <template #default="scope">
                {{ formatDate(scope.row.followUpDate, 'YYYY-MM-DD') }}
              </template>
            </el-table-column>
            <el-table-column label="随访形式" prop="followUpMode" width="150" align="center">
              <template #default="scope">
                {{ getDictLabel(DICT_TYPE.RANDOM_ACCESS_TYPE, scope.row.followUpMode) }}
              </template>
            </el-table-column>
            <el-table-column label="随访访视对象" prop="followUpTarget" width="150" align="center">
              <template #default="scope">
                {{ getDictLabel(DICT_TYPE.VISIT_TARGET, scope.row.followUpMode) }}
              </template>
            </el-table-column>
            <el-table-column label="面访形式" prop="faceToFaceMode" width="150" align="center"
              ><template #default="scope">
                {{ getDictLabel(DICT_TYPE.INTERVIEW_FORM, scope.row.faceToFaceMode) }}
              </template></el-table-column
            >
            <el-table-column label="失访原因" prop="lostContactReason" width="150" align="center"
              ><template #default="scope">
                {{ getDictLabel(DICT_TYPE.LOST_REASON, scope.row.lostContactReason) }}
              </template></el-table-column
            >
            <el-table-column
              label="下次随访日期"
              prop="nextFollowUpDate"
              width="150"
              align="center"
            >
              <template #default="scope">
                {{ formatDate(scope.row.nextFollowUpDate, 'YYYY-MM-DD') }}
              </template>
            </el-table-column>
            <el-table-column
              label="危险性评估"
              prop="riskAssessment"
              width="120"
              show-overflow-tooltip
              align="center"
              ><template #default="scope">
                {{ getDictLabel(DICT_TYPE.RISK_ASSESSMENT, scope.row.riskAssessment) }}
              </template></el-table-column
            >
            <el-table-column
              label="服药依从性"
              prop="medicationAdherence"
              width="120"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ getDictLabel(DICT_TYPE.MEDICATION_ADHERENCE, scope.row.medicationAdherence) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right" align="center">
              <template #default="scope">
                <el-button
                  v-hasPermi="['follow:up:details']"
                  type="primary"
                  link
                  @click="handleView(scope.row.id)"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <Pagination
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="getLists"
          />
        </div>
      </div>
    </ContentWrap>
    <RandomAccessDetail ref="randomAccessDetail" />
    <!-- 用户导入对话框 -->
    <RandomAccessImportForm ref="importFormRef" @success="getLists" />
  </div>
</template>
<script lang="ts" setup name="RandomAccess">
import * as RandomAccessApi from '@/api/patient/randomAccess'
import RandomAccessDetail from './components/randomAccessDetail.vue'
import { DICT_TYPE, getIntDictOptions, getDictLabel } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import RandomAccessImportForm from './components/randomAccessImportForm.vue'
const fileList = ref([])
const message = useMessage() // 消息弹窗
const exportLoading = ref(false) // 导出的加载中
// 选中的节点 ID
const selectedKeys = ref<string[]>([])
const queryParams = reactive({
  patientName: undefined,
  patientCode: undefined,
  idNumber: undefined,
  lastFollowupStime: '',
  lastFollowupEtime: '',
  followupDate: [],
  nextFollowupStime: '',
  nextFollowupEtime: '',
  nextFollowUpDate: [],
  medicationAdherence: undefined,
  currentOrgSubDbStatus: undefined,
  dangerousBehaviorsFlag: undefined,
  riskAssessment: undefined,
  currentSymptomsDetail: undefined,
  currentFollowupType: undefined,
  treatmentEffect: undefined,
  seclusionStatus: undefined,
  deptIds: [],
  lostContactReason: undefined,
  followUpMode: undefined,
  pageNo: 1,
  pageSize: 10
})
watch(
  () => [queryParams.lastFollowupStime, queryParams.lastFollowupEtime],
  ([newStime, newEtime]) => {
    queryParams.followUpDate = newStime && newEtime ? [newStime, newEtime] : []
  }
)

watch(
  () => [queryParams.nextFollowupStime, queryParams.nextFollowupEtime],
  ([newStime, newEtime]) => {
    queryParams.nextFollowUpDate = newStime && newEtime ? [newStime, newEtime] : []
  }
)
// 禁止选择晚于结束日期的开始时间
function lastFollowupDisableStartDate(date: Date) {
  if (queryParams.lastFollowupEtime) {
    return date.getTime() > new Date(queryParams.lastFollowupEtime).getTime()
  }
  return false
}

// 禁止选择早于开始日期的结束时间
function lastFollowupDisableEndDate(date: Date) {
  if (queryParams.lastFollowupStime) {
    return date.getTime() < new Date(queryParams.lastFollowupStime).getTime()
  }
  return false
}

// 禁止选择晚于结束日期的开始时间
function nextFollowupDisableStartDate(date: Date) {
  if (queryParams.nextFollowupEtime) {
    return date.getTime() > new Date(queryParams.nextFollowupEtime).getTime()
  }
  return false
}

// 禁止选择早于开始日期的结束时间
function nextFollowupDisableEndDate(date: Date) {
  if (queryParams.nextFollowupStime) {
    return date.getTime() < new Date(queryParams.nextFollowupStime).getTime()
  }
  return false
}
const loading = ref(true) // 列表的加载中
const lists = ref<any[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryFormRef = ref() // 搜索的表单
/** 查询列表 */
const getLists = async () => {
  loading.value = true
  try {
    const data = await RandomAccessApi.getRandomAccessList(queryParams)
    lists.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 查询按钮操作 */
const handleQuery = () => {
  getLists()
}

const randomAccessDetail = ref()
// 详情按钮操作
const handleView = (id: number) => {
  randomAccessDetail.value.open(id)
}
/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RandomAccessApi.exportPost(queryParams)
    download.excel(data, '随访信息模板.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 重置按钮操作 */
const resetQuery = () => {
  // 重置 lastFollowupStime, lastFollowupEtime, nextFollowupStime, nextFollowupEtime
  queryParams.lastFollowupStime = ''
  queryParams.lastFollowupEtime = ''
  queryParams.nextFollowupStime = ''
  queryParams.nextFollowupEtime = ''
  queryFormRef.value.resetFields()
  queryParams.patientCode = undefined
  handleQuery()
}
// 监听勾选的值
watch(selectedKeys, (newCheckedKeys) => {
  queryParams.deptIds = newCheckedKeys // 更新queryParams中的值
  handleQuery()
})
onMounted(() => {
  // 从 query 中获取 patientCode
  const route = useRoute()
  if (route.query.patientCode) {
    queryParams.patientCode = route.query.patientCode
  }
  getLists()
})
</script>

<style lang="scss" scoped>
.content {
  display: flex;
}
.tree-box {
  width: 330px;
  height: calc(100vh - 450px);
  overflow: auto;
  margin-right: 16px;
}
.upload-demo {
}
.time-box {
  display: flex;
  gap: 5px;
}
</style>
